package com.hp.tiger.concurrent.classloader.chapter4;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author XavierDong
 **/
public class DecryptClassloader extends ClassLoader {


    private static final String default_dir = "/Users/xavierdong/Documents/classloader1";


    private String dir = default_dir;


    public DecryptClassloader() {
    }

    public DecryptClassloader(ClassLoader parent) {
        super(parent);

    }


    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {

        String classPath = name.replace(".", "/");
        File classFile = new File(dir, classPath + ".class");

        if (!classFile.exists())
            throw new ClassNotFoundException("The Class " + name + " not found under directory [" + dir + "]");

        byte[] bytes = loadClassBytes(classFile);

        if (bytes == null || bytes.length == 0)
            throw new ClassNotFoundException("load the Class " + name + "  failed.");

        return this.defineClass(name, bytes, 0, bytes.length);
    }

    private byte[] loadClassBytes(File classFile) {

        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             FileInputStream fis = new FileInputStream(classFile)
        ) {

            int data;
            while ((data=fis.read())!=-1)
                baos.write(data ^ EncryptUtils.ENCRYPT_FACTOR);
            baos.flush();
            return baos.toByteArray();
        } catch (IOException e) {
            return null;
        }
    }

    public void setDir(String dir) {
        this.dir = dir;
    }
}
